#include <gio/gio.h>
#include <glib.h>
#define TCP_READ_MAX 255
void print_hex (gchar *pre, guint8 *buffer, gsize size)
{
  gsize i;

  g_print ("%s", pre);
  for (i = 0; i < size; i++) {
    g_print ("%02x ", buffer[i]);
  }
  g_print ("\n");
}

void
read_async_cb (GObject *source_object,
                        GAsyncResult *res,
                        gpointer user_data)
{
  g_debug ("L%d f-%s", __LINE__, __func__);
  GError *error = NULL;
  gsize bytes_read;
  guint8 *data = NULL;

  data = user_data;
  bytes_read = g_input_stream_read_finish (G_INPUT_STREAM (source_object), res,
      &error);
  g_assert_no_error (error);
  print_hex ("++++:", data, bytes_read);
  g_input_stream_read_async (G_INPUT_STREAM (source_object),
      data, TCP_READ_MAX, G_PRIORITY_DEFAULT,
      NULL, (GAsyncReadyCallback) read_async_cb, user_data);
}
int main (int argc, const char **argv)
{
  g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);
  GMainLoop *loop = NULL;
  GSocketClient *client = NULL;
  GSocketConnection *conn = NULL;
  GError *error = NULL;
  gchar *ip = "127.0.0.1";
  gint port = 14333;

  loop = g_main_loop_new (NULL, FALSE);
  client = g_socket_client_new ();
//  g_socket_client_set_timeout (client, 10);
  conn = g_socket_client_connect_to_host (client, ip, port, NULL, &error);
  if (!conn) {
    g_printerr ("can't connect");
  }
  GInputStream *istream = NULL;
  istream = g_io_stream_get_input_stream (G_IO_STREAM (conn));
  guint8 *data = NULL;
  data = g_new0 (guint8, TCP_READ_MAX);
  g_input_stream_read_async (istream, data, TCP_READ_MAX, G_PRIORITY_DEFAULT,
      NULL, (GAsyncReadyCallback) read_async_cb, data);
//write
  GOutputStream *ostream = NULL;
  char buffer[] = {0x10, 0x02, 0x01, 0x00, 0x03, 0x16};
  ostream = g_io_stream_get_output_stream (G_IO_STREAM (conn));
  g_output_stream_write_all_async(ostream, buffer, 6, G_PRIORITY_DEFAULT,
      NULL, NULL, NULL);
  g_print("loop\n");
  g_main_loop_run (loop);
  g_print("exit\n");
}
